package universum.engine.environment;

import ru.ksu.environment.NarrowEnvironment;
import ru.ksu.environment.P2PEnvironment;
import ru.ksu.environment.WideEnvironment;
import ru.ksu.environment.LocalEnvironment;
import universum.bi.Location;

import java.util.ArrayList;
import java.util.List;

public class MessagingService implements IMessagingService, IMessagingControl {
    private static MessagingService ourInstance = new MessagingService();
    private List<IEnvironmentServiceControl> _envList = new ArrayList<IEnvironmentServiceControl>();

    //public static IMessagingControl getInstance() {
    public static IMessagingService getInstance() {
        return ourInstance;
    }

    private MessagingService() {
         WideEnvironment wideEnv = new WideEnvironment(); // TODO: think about moving this line to EnvironmentService
        _envList.add(new EnvironmentService(wideEnv));
        NarrowEnvironment narrowEnv = new NarrowEnvironment();
        _envList.add(new EnvironmentService(narrowEnv));
        _envList.add(new EnvironmentService(new P2PEnvironment()));
        _envList.add(new EnvironmentService(new LocalEnvironment()));
    }

    public List<IEnvironmentService> getEnvironments(Location pos) {
        List<IEnvironmentService> result = new ArrayList<IEnvironmentService>();
        List<IEnvironmentServiceControl> envs = getSupportedEnvironments(pos);
        for (IEnvironmentServiceControl env : envs) result.add(env.getService());
        return result;
    }

    private List<IEnvironmentServiceControl> getSupportedEnvironments(Location pos){
        List<IEnvironmentServiceControl> result = new ArrayList<IEnvironmentServiceControl>();
        for(IEnvironmentServiceControl env : _envList)
        {
            if (true /*check if support*/) result.add(env);
        }
        return result;
    }
    public List<IAvailableMessage> getMessages(Location pos, int callerID) {
        List<IAvailableMessage> result = new ArrayList<IAvailableMessage> ();
        List<IEnvironmentServiceControl> envs = getSupportedEnvironments(pos);
        for (IEnvironmentServiceControl env : envs)
        {
            result.addAll(env.getMessages(pos, callerID)) ;
        }
        return result; 
    }
    public void preRound(int roundNumber)
    {
        for (IEnvironmentServiceControl env : _envList) env.preRound(roundNumber);
    }
    public void postRound()
    {
        for (IEnvironmentServiceControl env : _envList) env.postRound();
    }

}
